package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LearningServiceImpl implements LearningService {


    @Autowired
    MediaServiceClient mediaServiceClient;
    @Autowired
    ContentServiceClient contentServiceClient;
    @Autowired
    MyCourseTablesService myCourseTablesService;

    /**
     * 获取视频
     *
     * @param userId
     * @param courseId
     * @param teachplanId
     * @param mediaId
     * @return
     */
    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
        //查询课程消息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            XueChengPlusException.cast("该课程不存在");
        }
        //TODO:是否可以试学
        String teachplan = coursepublish.getTeachplan();
        List<TeachplanDto> teachplanDtos = JSON.parseArray(teachplan, TeachplanDto.class);
        if (teachplanDtos.size() <= 0 || teachplanDtos == null) {
            XueChengPlusException.cast("该课程不存在视频");
        }
        //将每一个小章节保存起来
        ArrayList<TeachplanDto> teachplanDtoArrayList = new ArrayList<>();
        teachplanDtos.forEach(teachplanDto -> {//遍历大章节
            //获取到每一个小章节
            List<TeachplanDto> teachPlanTreeNodes = teachplanDto.getTeachPlanTreeNodes();
            teachPlanTreeNodes.forEach(t->{
                teachplanDtoArrayList.add(t);
            });
        });
        //转化为map方便自己获取
        Map<Long, TeachplanDto> teachplanDtoMap = teachplanDtoArrayList.stream().collect(Collectors.toMap(TeachplanDto::getId, t -> t));
        TeachplanDto teachplanDto = teachplanDtoMap.get(teachplanId);
        if (teachplanDto==null){
            XueChengPlusException.cast("该章节没有视频");
        }
        String isPreview = teachplanDto.getIsPreview();
        if ("1".equals(isPreview)){//1表示支持试看
            //远程调用媒资获取视频播放地址
            RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
            return playUrlByMediaId;
        }

        //用户已登录
        if (StringUtils.isNotEmpty(userId)) {
            //查询是否存在学习资格
            //学习资格，[{"code":"702001","desc":"正常学习"},
            //{"code":"702002","desc":"没有选课或选课后没有支付"},
            //{"code":"702003","desc":"已过期需要申请续期或重新支付"}]
            XcCourseTablesDto courseTablesDto = myCourseTablesService.getLearningStatus(userId, courseId);
            String learnStatus = courseTablesDto.getLearnStatus();
            if (learnStatus.equals("702001")) {
                return mediaServiceClient.getPlayUrlByMediaId(mediaId);
            } else if (learnStatus.equals("702002")) {
                return RestResponse.validfail("无法观看，由于没有选课或选课后没有支付");
            } else if (learnStatus.equals("702003")) {
                return RestResponse.validfail("您的选课已过期需要申请续期或重新支付");
            }
        }
        //未登录或为选课判断是否收费
        //{code":"201000","desc":"免费"},{"code":"201001","desc":"收费"}
        String charge = coursepublish.getCharge();
        if (charge.equals("20100")) {
            //课程为免费--可以正常学习
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        return RestResponse.validfail("请购买课程后继续学习");
    }
}
